package com.echoesnet.echoesshortvideo.Activities;

import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.echoesnet.echoesshortvideo.Beans.IncludeNavBarBean;
import com.echoesnet.echoesshortvideo.Constant.CommonConstant;
import com.echoesnet.echoesshortvideo.R;
import com.echoesnet.echoesshortvideo.Utils.CommonUtils;
import com.echoesnet.echoesshortvideo.Utils.Image.GlideApp;
import com.echoesnet.echoesshortvideo.Utils.NetUtil;
import com.echoesnet.echoesshortvideo.Utils.SharePreUtils;
import com.echoesnet.echoesshortvideo.Utils.ToastUtils;
import com.echoesnet.echoesshortvideo.View.SwitchView;
import com.echoesnet.echoesshortvideo.ViewModels.SettingViewModel;
import com.echoesnet.echoesshortvideo.databinding.ActivityMySettingBinding;
import com.echoesnet.echoesshortvideo.views.dialog.CustomAlertDialog;
import com.echoesnet.echoesshortvideo.views.dialog.DownloadAlertDialog;


import org.json.JSONException;
import org.json.JSONObject;
import java.util.Map;
import io.reactivex.functions.Consumer;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

public class MySettingActivity extends BaseActivity
{
    private static final String TAG = MySettingActivity.class.getSimpleName();


    @BindView(R.id.iv_bind_phone)
    ImageView ivBindPhone;
    @BindView(R.id.rl_all_bindPhone)
    RelativeLayout rlAllBindPhone;

    @BindView(R.id.iv_message_come)
    SwitchView ivMessageCome;
    @BindView(R.id.rl_all_message_come)
    RelativeLayout rlAllMessageCome;
    @BindView(R.id.iv_mpdyfy_psd)
    ImageView ivMpdyfyPsd;
    @BindView(R.id.rl_all_modify_psd)
    RelativeLayout rlAllModifyPsd;
    @BindView(R.id.iv_black)
    ImageView ivBlack;
    @BindView(R.id.rl_all_blackManger)
    RelativeLayout rlAllBlackManger;
    @BindView(R.id.iv_feedback)
    ImageView ivFeedback;
    @BindView(R.id.rl_all_feedback)
    RelativeLayout rlAllFeedback;
    @BindView(R.id.iv_aboutwe)
    ImageView ivAboutwe;
    @BindView(R.id.rl_all_aboutwe)
    RelativeLayout rlAllAboutwe;
    @BindView(R.id.iv_check_new)
    ImageView ivCheckNew;
    @BindView(R.id.rl_all_check_new)
    RelativeLayout rlAllCheckNew;
    @BindView(R.id.tv_clearcache)
    TextView tvClearcache;
    @BindView(R.id.rl_all_clearcache)
    RelativeLayout rlAllClearcache;
    @BindView(R.id.rl_allinfor)
    RelativeLayout rlAllinfor;
    @BindView(R.id.tv_exitlogin)
    TextView tvExitlogin;
    @BindView(R.id.tv_bind_state)
    TextView tvBindState;
    private static final String STAT_ON = "1";
    private static final String STAT_OFF = "0";
    private Unbinder unbinder;

    private SettingViewModel setViewModel;
    private CustomAlertDialog dialog;
    private String mobile;
    private MySettingActivity mAct;
    private MyReceiver receiver;

    private ActivityMySettingBinding actBinding;
    private IncludeNavBarBean navBean;
    private boolean isFirstIn = false;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        actBinding = DataBindingUtil.setContentView(this, R.layout.activity_my_setting);
        navBean = new IncludeNavBarBean(getString(R.string.settings), true);
        actBinding.relNavBar.setNavBean(navBean);
        actBinding.relNavBar.itvLeft.setOnClickListener(view -> finish());


        unbinder = ButterKnife.bind(this);
        mAct = this;
        isFirstIn = true;
        receiver = new MyReceiver();
        setViewModel = ViewModelProviders.of(this).get(SettingViewModel.class);
        setViewModel.getNoticeStateBack().observe(mAct, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String s)
            {
                if (TextUtils.equals("1", s))
                    ivMessageCome.toggleSwitch(true);
                else
                    ivMessageCome.toggleSwitch(false);
            }
        });
        setViewModel.getSettingBack().observe(this, new Observer<Map<String, String>>()
        {
            @Override
            public void onChanged(@Nullable Map<String, String> sMap)
            {
                //更新UI
                mobile = sMap.get("mobile");
                String notice = sMap.get("notice");
                //未绑定
                tvBindState.setText((TextUtils.isEmpty(mobile) ? "未绑定" : "已绑定"));
                if (isFirstIn)
                {
                    if (TextUtils.equals(STAT_OFF, notice))
                    {
                        ivMessageCome.toggleSwitch(false);//关闭
                    } else if (TextUtils.equals(STAT_ON, notice))
                    {
                        ivMessageCome.toggleSwitch(true);//打开
                    }
                    isFirstIn = false;
                }

            }
        });
        setViewModel.getLogout().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String s)
            {
                if ("ok".equals(s))
                {
                    ToastUtils.showShort("退出成功");
                    Intent intent = new Intent(CommonConstant.REQUEST_LOGIN_CODE);
                    LocalBroadcastManager.getInstance(mAct).sendBroadcast(intent);
                    finish();
                }
            }
        });
        setViewModel.getVersionInfoBack().observe(this, new Observer<String>()
        {
            @Override
            public void onChanged(@Nullable String body)
            {
                try
                {
                    String message = "";

                    if (TextUtils.equals("{}", body) ||TextUtils.isEmpty(body))
                    {
                        message = "您当前已经是最新版本！";
                        if (dialog == null)
                        {
                            dialog = new CustomAlertDialog(MySettingActivity.this)
                                    .builder()
                                    .setBoldMsg(message)
                                    .setPositiveButton("确认", null)
                                    .setPositiveTextColor((ContextCompat.getColor(MySettingActivity.this, R.color.C0321)));
                        } else
                        {
                            dialog.show();
                        }
                    } else
                    {
                        JSONObject jsonObject = new JSONObject(body);
                    String version = jsonObject.getString("version");
                    String url = jsonObject.getString("url");
                    String type = jsonObject.getString("type");//是否强更(1:强更 0:选更)",
                    String desc = jsonObject.getString("desc");
                    if (CommonUtils.getVerCode(MySettingActivity.this) < Integer.parseInt(version))
                    {

                        message = "当前非最新版本\n" + "是否需要更新?";
                        if (dialog == null)
                        {
                            dialog = new CustomAlertDialog(MySettingActivity.this)
                                    .builder()
                                    .setBoldMsg(message)
                                    .setNegativeButton("取消", v ->
                                    {
                                    })
                                    .setNegativeTextColor(ContextCompat.getColor(MySettingActivity.this, R.color.C0322))
                                    .setPositiveButton("更新", v -> {
                                        String NetStat = "";
                                        //返回值 -1：没有网络  1：WIFI网络2：wap网络3：net网络
                                        int i = NetUtil.getNetworkStatus(MySettingActivity.this);
                                        switch (i)
                                        {
                                            case -1:
                                                NetStat = "没有网络";
                                                ToastUtils.showShort("当前无网络连接");
                                                break;
                                            case 1:
                                                NetStat = "WiFi网络";
                                                //WiFi网络
                                                showDownloadDialog(url);
                                                break;
                                            case 2:
                                            case 3:
                                                NetStat = "移动网络";
                                                new CustomAlertDialog(MySettingActivity.this)
                                                        .builder()
                                                        .setMsg(getString(R.string.mobie_net_tip))
                                                        .setTitle("提示")
                                                        .setPositiveButton("土豪请继续", new View.OnClickListener()
                                                        {
                                                            @Override
                                                            public void onClick(View v)
                                                            {
                                                                showDownloadDialog(url);
                                                            }
                                                        }).setNegativeButton("取消", new View.OnClickListener()
                                                {
                                                    @Override
                                                    public void onClick(View v)
                                                    {

                                                    }
                                                }).show();
                                                break;
                                        }
                                    })
                                    .setPositiveTextColor((ContextCompat.getColor(MySettingActivity.this, R.color.C0321)));
                        } else
                        {
                            dialog.show();
                        }
                    }
                    }
                    //显示版本信息

                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }
        });
        setViewModel.getClearBack().observe(this, new Observer<Long>()
        {
            @Override
            public void onChanged(@Nullable Long length)
            {
                long fileLengthMb = Math.round(length / 1024 / 1024);
                if (length != 0 && fileLengthMb == 0)
                    tvClearcache.setText(Math.round(length / 1024) + "KB");
                else
                    tvClearcache.setText(fileLengthMb + "MB");
            }
        });

        initView();
        setViewModel.getCatchFileLength();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(CommonConstant.REQUEST_LOGIN_CODE);
        LocalBroadcastManager.getInstance(mAct).registerReceiver(receiver, intentFilter);

    }

    @Override
    protected void onResume()
    {
        super.onResume();
        setViewModel.getSettingState();
        if (isFinish)
            finish();
    }
    private void showDownloadDialog(String url)
    {
        // 弹出下载Dialog
        new DownloadAlertDialog(MySettingActivity.this)
                .build()
                .setTitle("小录段子.apk")
                .setImage(R.mipmap.ic_launcher)
                .setDownLoadFileUrl(url)
                .show();
    }
    private void initView()
    {
        initListener();
    }

    private void initListener()
    {
        ivMessageCome.setOnStateChangedListener(new SwitchView.OnStateChangedListener()
        {
            @Override
            public void toggleToOn()
            {
                setViewModel.changeNoticeState(STAT_ON);
            }

            @Override
            public void toggleToOff()
            {
                setViewModel.changeNoticeState(STAT_OFF);
            }
        });
    }


    @Override
    public void onDestroy()
    {
        super.onDestroy();
        if (unbinder != null)
            unbinder.unbind();
        LocalBroadcastManager.getInstance(mAct).unregisterReceiver(receiver);
    }

    private boolean isFinish = false;

    private class MyReceiver extends BroadcastReceiver
    {
        @Override
        public void onReceive(Context context, Intent intent)
        {
            if (CommonConstant.REQUEST_LOGIN_CODE.equals(intent.getAction()))
            {
                isFinish = true;
            }
        }
    }

    @OnClick({ R.id.iv_bind_phone, R.id.rl_all_bindPhone, R.id.iv_message_come, R.id.rl_all_message_come, R.id.iv_mpdyfy_psd, R.id.rl_all_modify_psd, R.id.iv_black, R.id.rl_all_blackManger, R.id.iv_feedback, R.id.rl_all_feedback, R.id.iv_aboutwe, R.id.rl_all_aboutwe, R.id.iv_check_new, R.id.rl_all_check_new, R.id.tv_clearcache, R.id.rl_all_clearcache, R.id.rl_allinfor, R.id.tv_exitlogin})
    public void onClick(View view)
    {
        switch (view.getId())
        {
            case R.id.iv_bind_phone://手机号绑定
            case R.id.rl_all_bindPhone:
                if (TextUtils.isEmpty(mobile))
                {
                    Intent intent2 = new Intent(this, BindPhoneAct.class);
                    startActivity(intent2);
                } else
                {
                    String showPhone = mobile.substring(0, 3) + "********" + mobile.substring(8, mobile.length());
                    new CustomAlertDialog(MySettingActivity.this)
                            .builder()
                            .setTitle("更换已绑定的手机号？")
                            .setMsg("当前绑定的手机号为" + showPhone)
                            .setPositiveButton("更换", v -> {
                                Intent intent2 = new Intent(this, AlterBindPhoneAct.class);
                                intent2.putExtra("phone", mobile);
                                startActivity(intent2);
                            })
                            .setPositiveTextColor(ContextCompat.getColor(MySettingActivity.this, R.color.C0321))
                            .setNegativeButton("取消", v ->
                            {

                            })
                            .setNegativeTextColor(ContextCompat.getColor(MySettingActivity.this, R.color.C0322))
                            .show();
                }
                break;
            case R.id.iv_message_come://通知管理
            case R.id.rl_all_message_come:
                break;
            case R.id.iv_mpdyfy_psd://修改密码
            case R.id.rl_all_modify_psd:
                if (TextUtils.isEmpty(mobile))
                {
                    new CustomAlertDialog(mAct)
                            .builder()
                            .setCancelable(true)
                            .setMsg("当前未绑定手机号\n绑定后才可以操作哦")
                            .setPositiveButton("暂时不绑", v ->
                            {

                            })
                            .setNegativeButton("去绑定", v ->
                            {
                                Intent intent2 = new Intent(this, BindPhoneAct.class);
                                startActivity(intent2);
                            }).setNegativeTextColor(ContextCompat.getColor(mAct, R.color.black)).
                            setPositiveTextColor(ContextCompat.getColor(mAct, R.color.black))
                            .show();
                }
                else
                {
                    Intent intent2 = new Intent(this, AlterPassWordAct.class);
                    startActivity(intent2);
                }
                break;
            case R.id.iv_black://黑名单管理
            case R.id.rl_all_blackManger:
                Intent intent = new Intent(this, BlackMangerAct.class);
                intent.putExtra("uId", SharePreUtils.getUId());
                startActivity(intent);
                break;
            case R.id.iv_feedback://反馈与帮助
            case R.id.rl_all_feedback:
                Intent intent12 = new Intent(this, FeedBackActivity.class);
                startActivity(intent12);
                break;
            case R.id.iv_aboutwe://关于我们
            case R.id.rl_all_aboutwe:
                Intent intent1 = new Intent(this, AboutCompanyAct.class);
                startActivity(intent1);
                break;
            case R.id.iv_check_new://检查更新
            case R.id.rl_all_check_new:
                setViewModel.getVersionUpdate(CommonUtils.getVerCode(this) + "", "1");
                break;
            case R.id.tv_clearcache: //清除缓存的功能
            case R.id.rl_all_clearcache:
                showClearCatchDialog();
                break;
            case R.id.rl_allinfor:
                break;
            case R.id.tv_exitlogin://退出登录
                if (setViewModel != null)
                    setViewModel.logout();
                break;
        }
    }

    private void showClearCatchDialog()
    {
        if (!"0MB".equals(tvClearcache.getText().toString().trim()))
        {
            new CustomAlertDialog(this)
                    .builder()
                    .setTitle("提示")
                    .setMsg("确认要清除本地缓存数据吗？")
                    .setPositiveTextColor(Color.parseColor("#666666"))
                    .setPositiveButton("确认", new View.OnClickListener()
                    {
                        @Override
                        public void onClick(View v)
                        {
                            GlideApp.get(MySettingActivity.this).clearMemory();
                            clearCatch();
                        }
                    }).setNegativeButton("取消", new View.OnClickListener()
            {

                @Override
                public void onClick(View v)
                {

                }
            }).show();
        } else
        {
            ToastUtils.showShort("暂无缓存");
        }
    }

    private void clearCatch()
    {
        final String path = "";
        //遍历所有file下的文件
        Observable.create(new ObservableOnSubscribe<String>()
        {
            @Override
            public void subscribe(ObservableEmitter<String> e) throws Exception
            {
                Thread.sleep(2000);
                setViewModel.clearFile();
                e.onNext("");
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<String>()
                {
                    @Override
                    public void accept(String s) throws Exception
                    {
                        ToastUtils.showShort("清理成功");
                        tvClearcache.setText("0MB");
                    }
                });

    }
}
